package com.suntop.carousel.qlmediaplay.tools;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.text.TextUtils;
import android.util.Log;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.FutureTarget;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;

import java.io.File;

import wseemann.media.FFmpegMediaMetadataRetriever;
@SuppressLint("NewApi")
public class PictureCacheTool {
    private static PictureCacheTool instance;

    public static PictureCacheTool getInstance() {
        if (instance == null) {
            instance = new PictureCacheTool();
        }
        return instance;
    }
    public void loadPictureFirst(Context context,String videoUrl, String savePath,OnLoadPictureImageListener loadVideoImageListener) {
        PictureTask task = new PictureTask(context, loadVideoImageListener);
        task.execute(videoUrl, savePath);
    }


    public class PictureTask  extends AsyncTask<String,Integer, File>{
         private Context context;
         private OnLoadPictureImageListener loadPictureImageListener;

        public PictureTask(Context context, OnLoadPictureImageListener loadPictureImageListener) {
            this.context = context.getApplicationContext();
            this.loadPictureImageListener = loadPictureImageListener;
        }

        @Override
        protected File doInBackground(String... strings) {
            String url = strings[0];
            String path = (String) strings[1];
            File file = null;
            if (TextUtils.isEmpty(url)){
                return file;
            }
            String s = takeFileName(url);
            file = new File(path, s);
            if (file.exists() && file.length() > 20) {
                return file;
            }
            FutureTarget<Bitmap> submit = null;
            try {
               submit = Glide.with(context).asBitmap().load(url)
                        .submit(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL);
                file = FileUnit.saveBitmapFile(submit.get(),s,path);
            } catch (Exception exception) {
                exception.printStackTrace();
                Log.e("设置错误", exception + "");
            }finally {
                assert submit != null;
                submit.cancel(true);
            }
            return file;
        }
    }

    private String takeFileName(String url) {
        String s = FileUnit.takeFileName(url);
        String suffix = FileUnit.getSuffix(url);
        if (!TextUtils.isEmpty(suffix)) {
            s = "Cache_" + s.replace(suffix, "jpg");
        } else {
            s = "Cache_" + s + ".jpg";
        }
        return s;
    }

    public interface OnLoadPictureImageListener {
        void onLoadImage(File file);
    }
}
